<template>
  <div class="app-container">
  <!-- <t-Search /> -->
  <el-row>
    <el-col :span="22">
      <el-form :model="param" :inline="true" label-width="70px">
          <el-form-item label="单据号" style="width:351px">
              <el-input v-model.trim="param.returnBoxNo" clearable placeholder="请输入单据号"></el-input>
          </el-form-item>
          <el-form-item label="堆场名称" style="width:351px">
              <el-input v-model.trim="param.yardName" clearable placeholder="请输入堆场名称"></el-input>
          </el-form-item>
          <el-form-item label="单据类型" v-if="orderTypeval != '10'" style="width:351px">
            <el-select v-model="param.returnBoxType" clearable style="width:100%" placeholder="选择单据类型">
                <el-option v-for="item in param.returnTypeOptions" :key="item.value" :label="item.label" :value="item.value" />
            </el-select>
          </el-form-item>
          <el-form-item label="客户" style="width:351px">
              <el-input v-model.trim="param.agentName" clearable placeholder="请输入客户名称"></el-input>
          </el-form-item>
          <el-form-item label="订单号" style="width:351px">
              <el-input v-model.trim="param.orderNo" clearable placeholder="请输入订单号"></el-input>
          </el-form-item>
        </el-form>
    </el-col>
    <el-col :span="2">
        <el-row>
            <el-col :span="24" class="text-center"><el-button @click="handleReSet" :icon="Refresh">重置</el-button></el-col>
            <el-col :span="24" class="marginTop15 text-center"><el-button @click="getTableData" :icon="Search" type="primary">查询</el-button></el-col>
        </el-row>
    </el-col>
  </el-row>
  <!-- 5-还箱单 10-箱属 15-还箱令 -->
  <cz-tages :bottomLine="true" :typeList="typeList" @handleTypeChange="handleTypeChange" style="float: left;"></cz-tages>
  <span style="margin-top: -40px; float: right;">
      <el-button type="primary" @click="exportBoxList" size="small" plain round>导出</el-button>
      <el-button type="primary" @click="goCreateReturn(5)" size="small" plain round>开还箱单</el-button>
      <el-button type="primary" @click="goCreateReturn(15)" size="small" plain round>开还箱令</el-button>
      <el-button type="primary" @click="goCreateReturn(10)" size="small" plain round>开箱属</el-button>
  </span>

  <Table ref="tableRef" v-bind="table" style="width: 100%;" @pageChange="onTablePageChange" @showInfo="showInfo" @downloadFile="downloadFile" 
  @showReturnRecord="showReturnRecord" @preview="preview" @activeAddPacking="activeAddPacking"  :disableHeaderCheckbox="disableHeaderCheckbox"></Table>

  <!-- 集装箱选择 -->
  <el-drawer v-model="param.drawerSelectBox" :with-header="false" size="35%">
    <span class="_before">集装箱选择</span>
    <el-input v-model.trim="param.containerNos" @input="getBoxTableData" type="text" placeholder="请输入箱号 HNKU0000000,HNKU0000000" style="float: right;margin-top: 40px;" />
    <div style="height:40px"></div>
    <el-table :data="param.selectBoxTable" @selection-change="handleSelectionBoxChange" style="margin-top: 80px;">
        <el-table-column type="selection" width="50" align="center"/>
        <el-table-column prop="containerNo" label="箱号" width="120"  align="center"> </el-table-column>
        <el-table-column prop="boxType" label="箱型"  align="center">
          <template #default="scope">{{ basicConfig.boxTypeInfo1[scope.row.boxType] }}</template>
        </el-table-column>
        <el-table-column prop="agentName" label="客户" width="200" align="center"> 
            <template #default="scope">
              <el-tooltip :content="scope.row.agentName" placement="top">
                  <span class="text-ellipsis">{{scope.row.agentName || '--'}}</span>
              </el-tooltip>
            </template>
        </el-table-column>
        <el-table-column prop="agentUserName" label="联系人"  align="center"></el-table-column>
        <el-table-column prop="returnCity" label="还箱城市" width="200"  align="center">
          <template #default="scope">
            <template v-if="splitSrray(scope.row.returnCity) == '--'">--</template>
            <template v-else>
              <el-tooltip :content="splitSrray(scope.row.returnCity)" placement="top">
                  <span class="text-ellipsis">{{splitSrray(scope.row.returnCity)}}</span>
              </el-tooltip>
            </template>
          </template>
        </el-table-column>
        <!-- <el-table-column prop="boxEastUserName" label="操作人"  align="center"> </el-table-column> -->
    </el-table>
    <div style="margin-top: 40px;height: 50px;">
      <el-button @click="handleChoiceBox" type="primary" style="float: right;width: 100px;"> 确定 </el-button>
    </div>
  </el-drawer>

  <!-- 开还箱单 -->
  <el-drawer v-model="param.drawer1" :with-header="false" :before-close="close" :show-close="false" size="40%">
    <el-row>
      <el-col :span="6">
        <span class="_before" v-if="param.oprType == 5">开还箱单</span>
        <span class="_before" v-else-if="param.oprType == 10">开箱属</span>
        <span class="_before" v-else-if="param.oprType == 15">开还箱令</span>
      </el-col>
    </el-row>
    <el-row class="marginTop10">
      <el-col :span="4" class="_asterisk">箱号</el-col><el-col :span="12" :offset="8" class="text-right"><el-button @click="choiceBox" size="small" icon="edit">选择箱号</el-button></el-col>
      <el-col :offset="1" :span="23" class="marginTop10">
        <el-row>
          <template v-if="selectBoxList && selectBoxList.length > 0">
              <el-col v-for="(item,index) in selectBoxList" :span="6" :key="index" class="containerNo-border">{{item.containerNo}}</el-col>
          </template>
          <template v-else>
            <el-col :span="24" class="text-center" style="color: #2158F3;">请先选择箱号</el-col> 
          </template>
        </el-row>
      </el-col>
    </el-row>
    <el-form :model="param" ref="returnFormRef" label-width="auto" :rules="returnRules" class="marginTop20">
      <el-form-item label="箱型/箱量">{{param.boxTypeNum}}</el-form-item>
      <el-form-item label="还箱城市">{{returnCityStr}}</el-form-item>
      <el-form-item label="堆场名称"  prop="yardName_">
        <yardSelect ref="selectRef" v-model="param.yardName_" :yardName="param.yardName_"  :selectName="'yardName'" :needInfo="true" @yardId="yardInfoData"
          style="width:100%" :placeholder="'请输入堆场名称'">
        </yardSelect>
      </el-form-item>
      <el-form-item label="堆场地址" prop="yardAddress">
        <el-input v-model="yardInfo.yardAddress" disabled style="width: 100%;" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item label="堆场作业时间" prop="workTime"> 
        <el-input v-model="yardInfo.workTime" disabled style="width:100%" placeholder="请输入" />
      </el-form-item>

      <template v-if="param.oprType == 5">
        <el-form-item label="还箱指令号" prop="instruction">
          <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="还箱单有效期范围" prop="returnValidityPeriod">
          <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
      </template>
      <template v-if="param.oprType == 15">
        <el-form-item label="还箱指令号">
          <el-input v-model="param.instruction" style="width: 100%;" placeholder="请输入"></el-input>
        </el-form-item>
        <el-form-item label="还箱单有效期范围">
          <el-date-picker v-model="param.returnValidityPeriod" type="daterange" range-separator="~"
            start-placeholder="开始日期" end-placeholder="结束日期" style="width: 100%;" />
        </el-form-item>
      </template>
      <template v-if="param.oprType != 10">
        <el-form-item label="联系人" prop="contacts">
          <el-select v-model="yardInfo.contacts" @change="handleYardContactsChange">
            <el-option v-for="item in yardInfo.yardContacts" :key="item.yardContactSerialNo" :label="item.contacts"
              :value="item">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="联系电话" prop="tel">
          <el-input v-model="yardInfo.tel" disabled style="width: 100%;" placeholder="请输入">
            <template #prepend v-if="yardInfo?.areaCode">+{{yardInfo.areaCode}}</template>
          </el-input>
        </el-form-item>
      </template>
      
      
      <el-form-item v-if="param.oprType == 10" label="箱属内容" prop="boxOwnerContent">
          <el-input v-model="param.boxOwnerContent" type="textarea" maxlength="2000" show-word-limit  rows="5" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item v-if="param.oprType != 10" label="箱令内容" prop="boxOwnerContent">
          <el-input v-model="param.boxOwnerContent" type="textarea" maxlength="2000" show-word-limit  rows="5" placeholder="请输入"></el-input>
      </el-form-item>
      <el-form-item :label="returnTypeFilter(param.oprType)+'附件'">
          <ImgUpload ref="packingRef" :urlList="fileList" :limit="10" :type="'jpg/png/jpeg/pdf/zip'" :displayType="3" :drag="true" :showNumber="4"></ImgUpload>
      </el-form-item>
    </el-form>    
    <div style="margin-top: 40px;height: 50px;">
      <el-button @click="handleSubmit" type="primary" style="float: right;width: 100px;">提交</el-button>
    </div>
  </el-drawer>

  <!-- 还箱记录 -->
  <el-drawer v-model="param.drawer3" :with-header="false">
    <span style="font-weight: 700;font-size: 15px;">
      <span style="width:3px;height:20px;background-color: #2158F3;"> &nbsp</span>还箱记录
    </span>
    <div style="float: right;margin-top: 60px;">
      <span>应还箱量：{{ rowData.totalReturnQuantity }} 个</span> &nbsp;
      <span>实还箱量：{{ rowData.returnedQuantity }} 个</span>
    </div>
    <el-table :data="packingRecord" style="margin-top: 100px;">
      <el-table-column prop="containerNo" label="箱号" />
      <el-table-column prop="boxType" label="箱型" />
      <el-table-column prop="returnDate" label="还箱日期" />
      <el-table-column prop="agentName" label="租客" />
    </el-table>
  </el-drawer>
  <!-- 还箱单详情 -->
  <IndexInfo ref="indexInfoRef" :isAgent="false"></IndexInfo>

  </div>
</template>

<script setup lang="ts">
import { downloadIamge } from '@/utils/download'
import Table from '@/components/table'
import { formatDate } from '@/utils'
import czTages from '@/components/chengzhiTags'
import ImgUpload from '@/components/upload/uploadFiles-Images'
import IndexInfo from '@/views/components/huanXiangManage/indexInfo.vue'
import basicConfig from '@/constant/containerInfo'

import { getBoxEastTable, addReturn,exportBoxEastReturnBoxList,boxEastStatusCount } from '@/api/orderManage/returnBox'
import {downloadFile as globalDownloadFile} from '@/utils/download'
import { getDetailTable} from '@/api/orderManage/returnBoxDetail'
import yardSelect from '@/components/citySelect/yardSelect.vue';
import { returnPage} from '@/api/boxManage/index'
import { computed, getCurrentInstance, onMounted, onActivated, reactive, ref, watch,nextTick } from 'vue';
import { useRoute } from 'vue-router'

import {
  Plus,
  Delete,
  Edit,
  Message,
  Search,
  Download,
  Upload,
  Refresh,
  UploadFilled,
  ChatLineSquare,
  SwitchButton
} from '@element-plus/icons-vue'
import { ElMessage,ElMessageBox } from 'element-plus'

const param = reactive({
  pageNum: 1,
  pageSize: 10,
  returnBoxType: '',
  //table
  boxCaseOptions: [ //5-全新   10-次新  15-适货 20-混提(次新或者适货)
    { value: '15', label: '适货', },
    { value: '10', label: '次新', },
    { value: '20', label: '混提', },
    { value: '5', label: '全新', },
  ],
  boxTypeOptions: [ // 5 - 40HQ   10 - 40GP  15 - 20HQ   20 - 20GP
    { value: '5', label: '40HQ', },
    { value: '10', label: '40GP', },
    { value: '15', label: '20HQ', },
    { value: '20', label: '20GP', },
  ],
  returnTypeOptions: [ //5-还箱单 10-箱属  15-还箱令
    // { value: '5', label: '还箱单', },
    { value: '10', label: '箱属', },
    { value: '15', label: '还箱令', },
  ],
  //开还箱单列表
  // rentOrderTable: [{ orderNo: '', planPickupDate: '', createTime: '' }],
  rentOrderTable: [],
  rentBoxTable: [{ boxType: '', boxQuantity: '', boxCondition: '' }],
  selectTable: [{ orderNo: '', planPickupDate: '', createTime: '', boxType: '', boxQuantity: '', boxCondition: '' }],
  selectBoxTable: [{ containerNo: '', boxType: '', inDays: '', boxCondition: '' }],
  isExist:false,
  boxTypeNum:'--'
});
const table = reactive({
  // 列表数据（必传）
  data: [],
  // 表头内容（必传，注意格式）
  header: [
    { key: 'returnBoxNo', colWidth: '200', title: '单据号', type: '<a>', command: 'showInfo', isCheck: true },
    { key: 'orderList', key2: 'orderNo', colWidth: '200', title: '订单号', type: '/', isCheck: true },
    { key: 'returnBoxType', colWidth: '80', title: '单据类型', type: 'filter', filter: { 5: '还箱单', 10: '箱属', 15: '还箱令' }, isCheck: true },
    { key: 'yardName',colWidth: '150', title: '堆场名称', type: 'text', isCheck: true },
    { key: 'totalReturnQuantity', colWidth: '80', title: '总箱量', type: 'totalQuantity', isCheck: true },
    { key: 'returnedQuantity', colWidth: '80', title: '已提箱量', type: 'totalQuantity', isCheck: true },
    { key: 'totalQuantity',key2: 'packedQuantity', colWidth: '80', title: '未提箱量', type: 'quantity', isCheck: true },
    { key: 'returnValidityPeriodStart', colWidth: '200', key2: 'returnValidityPeriodEnd', title: '还箱单据有效期范围', type: 'range', isCheck: true },
    { key: 'residueReturnDays', colWidth: '140', title: '还箱令有效期天数',type: 'days', after: '天', isCheck: true },
    { key: 'agentName', title: '客户',colWidth: '250', type: 'text', isCheck: true },
    { key: 'agentUserName', title: '联系人',colWidth: '80', type: 'text', isCheck: true },
    { key: 'agentUserTel',colWidth: '140', title: '联系电话', type: 'phoneNumber',areaCode:"agentUserAreaCode", isCheck: true },
    { key: 'status', colWidth: '80', title: '状态', type: 'statusHuanxiang', isCheck: true },
    {
      key: 'operate',
      colWidth: '150',
      title: '操作',
      type: 'operate',
      isCheck: true,
      fixed: 'right',
      buttons: [
        {
          // icon: 'Download',
          command: 'downloadFile',
          // content: '下载还箱单',
          name:'下载',
          isShow: (row: any) => {
            return JSON.parse(row.pdfFile)!='';
          },
        },
        { 
            command: 'preview',
            name:'预览'
        },
        {
          command: 'showReturnRecord', 
          name:'还箱记录',
        },

      ],
    },
  ],
  // table配置项（必传）
  config: {
    isSelection: true,
    isList: false,
    isPagination: true, // 是否分页
    total: 0, // 分页总数
    loading: false
  },
});

//校验规则
const validatePlanPackingDate = (rule: any, value: any, callback: any) => {
  if (value[0] < new Date(new Date().setHours(0, 0, 0, 0))) {
    return callback(new Error('开始日期须 大于等于 今天'))
  }
  return callback()
}
//堆场组件 emit 
const yardInfo = ref({})
const returnRules = {
  yardName_: [{ required: true, trigger: "change", message: "不能为空" }],
  instruction: [{ required: true, trigger: "blur", message: "不能为空" }],
  returnValidityPeriod: [
    { required: true, trigger: "blur", message: "不能为空" },
    { required: true, validator: validatePlanPackingDate, trigger: "blur" }
  ],
  'yardInfo.value.yardAddress':[{ required: true, trigger: "change", message: "不能为空" }],
  'yardInfo.value.tel': [{ required: true, trigger: "change", message: "不能为空" }],
  'yardInfo.value.contacts': [{ required: true, trigger: "change", message: "不能为空" }],
  'yardInfo.value.workTime': [{ required: true, trigger: "change", message: "不能为空" }],
  boxOwnerContent: [{ required: true, trigger: "change", message: "不能为空" }],
}

// const typeList = computed(() => {
//   const list = [{ id: 0, name: '全部' }, { id: 5, name: '已发放' }, { id: 10, name: '已下载' }, { id: 15, name: '还箱中' },{ id: 20, name: '已完成' }]
//   return list
// })

const typeList = ref([
    { id: 0, name: '全部',num:0 },
    { id: 5, name: '已发放',num:0 },
    { id: 10, name: '已下载',num:0 },
    { id: 15, name: '还箱中',num:0 },
    { id: 20, name: '已完成',num:0 },
])

// 还箱单状态: 5-已发放 10-已下载 15-还箱中 20-已完成 25-已过期
// 查询各还箱状态的数量
const getBoxEastStatusCount = async(data:any) => { 
  await boxEastStatusCount(data).then((res: any) => {
    if(res.code == '00000'){
      typeList.value.forEach(item => { 
        item.num = 0
        res.data.forEach(item1 => { 
          if(item.id == 0){ //全部
            item.num += item1.totalQty
          }else if(item.id == 5 && item1.status == 5){ //已发放
              item.num += item1.totalQty
          }else if(item.id == 10 && item1.status == 10){ //已下载
              item.num += item1.totalQty
          }else if(item.id == 15 && item1.status == 15){ //还箱中
              item.num += item1.totalQty
          }else if(item.id == 20 && item1.status == 20){ //已完成
              item.num += item1.totalQty
          }
        })
      })
    }
  })
}
const route = useRoute()
const orderTypeval = ref("")

onActivated(() => {
   if(route.query.refNo){
    param.returnBoxNo=route.query.refNo
  }
   nextTick(() => {
       if(route.name=='JKhuanXiangManageXD4'){
          orderTypeval.value = "10"
        }else{
          orderTypeval.value = "5"
        }
    getTableData()
    })
})

// //监听 tagName
// import orderInfo from '../../../store/modules/order'
// watch(() => orderInfo().tagName, (val: any) => {
//   console.log(val)
//   param.tagName = val
//   getTableData();
// },{immediate:true})
// 获取路径参数和查询参数
// const paramsAndQuery = computed(() => ({
//   query: route.name
// }));
// watch(
//   paramsAndQuery,
//   (newVal, oldVal) => {
//     if(newVal.query=='JKhuanXiangManageXD4'){
//       param.tagName = 'returnBox'
//     }else{
//       param.tagName = 'rent'
//     }
//   getTableData()
//   },
//   {immediate:true}
// );
function handleTypeChange(val: any) {
  param.status = val
  getTableData()
}

function getTableData() {
  let data = {
    pageNum: param.pageNum,
    pageSize: param.pageSize,
    returnBoxNo: param.returnBoxNo,
    yardName: param.yardName,
    orderType:orderTypeval.value,
    returnBoxType: param.returnBoxType,
    status: param.status,
    orderNo: param.orderNo,
    agentName: param.agentName,
  }
  
  table.config.loading = true;
  // 获取列表数据
  getBoxEastStatusCount(data)
  getBoxEastTable(data).then((res: any) => {
    table.data = res.data.list;
    table.data.forEach((item: any) => {
      let orderList = JSON.parse(item.orderList)
      item.orderNoList = orderList.map((item: any) => item.orderNo).join('/')
    })
    table.config.total = res.data.total;
  })
  table.config.loading = false;
}
function handleReSet() {
  param.returnBoxNo = null
  param.yardName = null
  param.returnBoxType = ''
  param.status = null
  param.agentName = null
  param.orderNo = null
  getTableData()
}

//分页
function onTablePageChange(page: any) {
  param.pageNum = page.pageNum;
  param.pageSize = page.pageSize;
  getTableData();
};

//下载还箱单
const downloadFile = (rowData: any) => {
  // let fileListStr = ''
  //   if(rowData.returnBoxType == 10 ){ //箱属
  //       fileListStr = rowData.pdfFile
  //   }else{ // 还箱单/还箱令
  //       fileListStr = rowData.detailFileList
  //   }
   let fileListStr = rowData.detailFileList
    if (fileListStr) {
        const fileListObj = JSON.parse(fileListStr)
        if (fileListObj.length < 1 || !fileListObj[0].url) return ElMessage.warning('没有找到还箱单')
        downloadIamge(fileListObj[0].url,fileListObj[0].originalFileName || new Date(Date.now()+28800000).toISOString())
    } else {
        ElMessage.error('没有找到还箱单')
    }


  // if (fileListStr) {
  //   let pdfFile = JSON.parse(fileListStr)
  //   pdfFile=pdfFile[0]
  //   if (!pdfFile.url) return ElMessage.error('chengzhi 未找到文件')
  //   downloadIamge(pdfFile.url,pdfFile.originalFileName || new Date(Date.now()+28800000).toISOString())
  // } else {
  //   // console.log(rowData)
  //   ElMessage.error('chengzhi 未找到文件')
  // }
}

// 添加还箱记录
const rowData = ref({})
const activeAddPacking = (row: any) => {
  rowData.value = row
  let boxType = JSON.parse(rowData.value.containerCountList)[0].boxType
  rowData.value.boxType = boxTypeFilter(boxType)

  param.drawerReturnBox = true
}

//查看还箱记录
const packingRecord = ref([])
const showReturnRecord = (row: any) => {
  param.drawer3 = true
  rowData.value = row
  const data = {
    pageNum: 1,
    pageSize: 200,
    returnBoxId: row.id
  }
  getDetailTable(data).then((res: any) => {
    let list = res.data.list
    list.forEach((item: any) => {
      item.boxCondition = boxConditionFilter(item.boxCondition)
      item.boxType = boxTypeFilter(item.boxType)
      item.returnDate = formatDate(item.returnDate, 2)
    })
    packingRecord.value = list

  })
}


//查看还箱单详情
const indexInfoRef=ref()
const showInfo = (row: any) => {
  indexInfoRef.value.openBox(row)
};
const preview = (row: any) => {
  indexInfoRef.value.openBox(row)
}
//关闭弹框
const returnFormRef=ref()
const fileList=ref([]) //附件默认
const close = () => {
  // returnFormRef.value.resetFields()
  param.rentOrderTable=[]
  param.returnValidityPeriod=[]
  param.instruction=null
  param.yardName_=null
  yardInfo.value = {}
  selectBoxList.value=[]
  fileList.value=[]
  param.drawer1 = false;
  param.drawer2 = false
  param.drawer3 = false
  packingRef.value?.clearFiles()
}
// 去开还箱单(//param.oprType 5-还箱单 10-箱属 15-还箱令  )
const goCreateReturn = (type: number) => {
  param.drawer1 = true
  param.oprType = type
  param.rentBoxTable = []
}
const { proxy } = getCurrentInstance();
const handleSubmit = () => {
  proxy.$refs.returnFormRef.validate(valid => {
    if (!valid) return
    handleAddReturn()
  })
}
//开还箱单 orderList
const tableRef = ref({ multipleSelection: [] });
const packingRef = ref()
const orders = ref([])
const selectRef = ref()
const handleAddReturn = async () => {
  // let orders = JSON.parse(JSON.stringify(param.rentOrderTable)) //订单list 
  if (!orders.value[0] || !orders.value[0].orderNo) {
    ElMessage.warning("订单不能为空！")
    return
  }
  // const imgList = await packingRef.value.fileList || []
  // if (param.oprType > 5 && imgList.length == 0) {
  //   ElMessage.warning("附件不能为空！")
  //   return
  // }
  let orderList: any = []
  let containerNoList: any[] = []
  let containerCountList: any[] = []
  orders.value.forEach((el: any) => {
    // orderList.push({ "orderId": el.orderId, "orderNo": el.orderNo, "returnValidityPeriod": param.returnValidityPeriod }) // 大BUG
    orderList.push({ "orderId": el.orderId, "orderNo": el.orderNo })
  })
  const countByCategory1 = orders.value.reduce((acc, item) => {
    acc[item.boxType] = (acc[item.boxType] || 0) + 1;
        return acc;
    }, {} as Record<string, number>);
    for (const key in countByCategory1) {
        // 使用类型断言确保类型安全
        const value = countByCategory1[key];
        const items = {
            boxType:key,
            boxQuantity:String(value)
        }
        containerCountList.push(items)
    }


  selectBoxList.value.forEach((el: any) => {
    containerNoList.push({ "containerId": el.id, "containerNo": el.containerNo })
  })
  const data = {
    returnBoxType: param.oprType,
    boxEastYardId: yardInfo.value.id,
    orderList: JSON.stringify(orderList), //"[{\"orderId\":1,\"orderNo\":\"2222\"}]", ？
    containerNoList: JSON.stringify(containerNoList), //"[{\"containerId\":1,\"containerNo\":\"2222\"}]",
    containerCountList: JSON.stringify(containerCountList), //"[{\"boxType\":5,\"boxCondition\":\"10\",\"boxQuantity\":\"11\"}]" ？
    detailFileList: JSON.stringify(packingRef.value.fileList) || null,
    yardContactSerialNo: yardInfo.value.yardContactSerialNo
  }

  if (param.returnValidityPeriod && param.returnValidityPeriod.length == 2) {
    data.returnValidityPeriodStart = param.returnValidityPeriod[0]
    data.returnValidityPeriodEnd = param.returnValidityPeriod[1]
  }

  if (param.oprType == 5) {  // 5-还箱单(回调箱) 10-箱属(租箱) 15-还箱令(租箱)  
    data.instruction = param.instruction //指令号
    data.containerClassify = 10  //集装箱分类(5-租箱 10-回调)
  }
  if (param.oprType == 10) {
    data.boxOwnerContent = param.boxOwnerContent
    // data.detailFileList = null
    data.containerClassify = 5
  }
  if (param.oprType == 15) {
    // data.detailFileList = null
    data.instruction = param.instruction //指令号
    data.containerClassify = 5
  }
  
  addReturn(data).then((res: any) => {
    if(res.code == '00000'){
      param.returnId = res.data.id
      ElMessage.success('还箱单已生成')
      close()
      getTableData()
    }
    
  })
  selectRef.value?.forceClear()
  param.boxOwnerContent = ''
  yardInfo.value.id = ''
  returnCityId.value = ''
}

//选择集装箱
const returnCityStr = ref('--')
const choiceBox = () => {
  param.isExist = true
  getBoxTableData()
  param.boxTypeNum  = '--'
  returnCityStr.value = '--'
  param.drawerSelectBox = true
}
let selectBoxList = ref([])

const handleChoiceBox = () => {
  let returnCityArr = []
  // let arry: any = []
  selectBoxList.value.forEach((el: any) => {
    let cityStr = JSON.parse(el.returnCity)
    if(cityStr){
      returnCityArr = returnCityArr.concat(cityStr)
    }
    returnCityArr = Array.from(
      new Map(returnCityArr.map(item => [item.returnCityId, item])).values()
    );
    // arry.push(el.orderId)
  })
  // arry = [...new Set(arry)]
  returnCityStr.value = splitSrray(returnCityArr)
  orders.value = Array.from(
      new Map(selectBoxList.value.map(item => [item.orderId, item])).values()
    );



  param.drawerSelectBox = false
}

const handleSelectionBoxChange = (list: any) => {
  selectBoxList.value = list
  getFormatNum(list)
 
}
const yardInfoData = (id: string, info: any) => {
  // param.location = id
  if (info) {
    param.yardName_ = info.yardName
    yardInfo.value = info
    yardInfo.value.yardContacts = info.yardContacts ? JSON.parse(info.yardContacts) : []
    //获取联系人&&默认第一个
    handleYardContactsChange(yardInfo.value.yardContacts[0])
  }
}

//获取 箱子列表
import useUserStore from '@/store/modules/user'
const userStore = useUserStore()
const returnCityId = ref('')
function getBoxTableData() {
  const containerNos = getContainerNos()
  let orderIds: any = []
  returnCityId.value = yardInfo.value?.cityId || ''
  if(param.oprType == 5 && orderTypeval.value=='10'){
    returnCityId.value = ''
  }

  let data = {
        statusList: [20], //集装箱 未还
        containerNos: containerNos.length > 1 ? containerNos : [],
        containerNo: containerNos.length == 1 ? containerNos[0] : null,
        orderType: 5,
        // returnCityId: returnCityId.value,
        returnCityId:null,
        boxEastOperatorUserId: userStore.getUser().id,
        pageNum: 1,
        pageSize: 10000,
    };

    returnPage(data).then(res => {
      let list = res.data.list;
      param.isExist = false
      // list.forEach((el: any) => {
      //   el.boxType = boxTypeFilter(el.boxType)
      //   el.boxCondition = boxConditionFilter(el.boxCondition)
      // });
      param.selectBoxTable = list;
    });
  }

// 获取箱号
const getContainerNos = () => {
  let containerNos = [] //param.containerNos ? param.containerNos.split(",") :
  if (param.containerNos) {
    const dos = param.containerNos.indexOf(",") > -1 ? ',' : '，'
    containerNos = param.containerNos.split(dos).map((item) => item.trim())
  }
  return containerNos
}

//箱型量
const getFormatNum = (arry: any) => {
  let str = ''
  let typeList: any = []
  // if (arry.length == 0 || !arry[0].orderNo) return 0 // 过滤初始值影响 { orderNo: '', planPickupDate: '', createTime: '' }
  arry.forEach((el) => {
    if (!typeList.includes(el.boxType)) {
      typeList.push(el.boxType)
    }
  })
  typeList.forEach((el) => {
    let num = 0
    arry.forEach((el2) => {
      if (el2.boxType == el) {
        num += 1
      }
    })
    let dos = str == '' ? '' : '、'
    // str = str + dos + boxTypeFilter(el) + '*' + num
    str = str + dos + basicConfig.boxTypeInfo1[el] + '*' + num
  })
  if (str) {
    param.boxTypeNum = str
    return str
  } else {
    return 0
  }
}

//联系人切换
const handleYardContactsChange = (val: any) => {
  if (!val) return
  yardInfo.value.contacts = val.contacts
  param.contacts = val.contacts // to pass jiaoyan
  yardInfo.value.tel = val.tel
  yardInfo.value.areaCode = val.areaCode
  yardInfo.value.email = val.email
  yardInfo.value.yardContactSerialNo = val.yardContactSerialNo
}

//过滤
const boxTypeFilter = (val: any) => {
  let result = ''
  const boxConditionList = [{ value: 5, label: '40HQ' }, { value: 10, label: '40GP' }, { value: 15, label: '20HQ' }, { value: 20, label: '20GP' }]
  boxConditionList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
const boxConditionFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 15, label: '适货' }, { value: 10, label: '次新' }, { value: 20, label: '混提' },{ value: 5, label: '全新' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}
//  //5-还箱单 10-箱属  15-还箱令
const returnTypeFilter = (val: any) => {
  let result = ''
  const boxTypeList = [{ value: 5, label: '还箱单' }, { value: 10, label: '箱属' }, { value: 15, label: '还箱令' }]
  boxTypeList.forEach((item: { value: any; label: any; }) => {
    if (item.value == val) {
      result = item.label
    }
  })
  return result
}

// 导出还箱单
const disableHeaderCheckbox = ref(false) // true:禁用表头全选/全取消 选择框 false:开启 表头全选/全取消 选择框
const exportBoxList = () => {
  const checkAllItem = tableRef.value.multipleSelection
  const ids = checkAllItem.map((item: any) => item.id)
  if (ids.length < 1) return ElMessage.warning('请选择需要导出的还箱单！')
  ElMessageBox.confirm('确认要导出选中的还箱单数据', '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => {
    const data = {returnBoxListIds:ids}
    exportBoxEastReturnBoxList(data).then((res: any) => {
      globalDownloadFile(res,'租箱还箱单信息')
    }).catch((error: any) => {
      ElMessage.error(error)
    })
  }).catch(() => {
  });
}

// 多个城市拼接
const splitSrray = (row:any) => {
  let newRow = []
  try{
    newRow = JSON.parse(row) || []
  }catch(e){
    newRow = row || []
  }
  let newRowStr = ''
  const newRowLength = newRow.length
  newRow.forEach((item,index) => { 
    if(index < newRowLength - 1){
      newRowStr += item.returnCityName + "、"
    }else{
      newRowStr += item.returnCityName
    } 
  })
  return newRowStr || '--'
}
</script>

<style lang="scss" scoped>
.el-form-diy {
  padding: 10px;

  div {
    width: 100%;
  }
}
.title-left{
  font-weight: 600;
  color: #605266;
}
.containerNo-border{
  border: 1px solid #ebeef5;
  text-align: center;
}
</style>